import { ModalFooterSchema } from '../schema/schema';
import { BuilderHTMLElement, FarrisDesignBaseNestedComponent } from '@farris/designer-element';
import { ElementPropertyConfig } from '@farris/ide-property-panel';
import { ModalFooterProp } from '../property/property-config';
import { FormPropertyChangeObject } from '../../../../entity/property-change-entity';
import FdHeaderToolBarComponent from '../../header/component/fd-header-toolbar';
import { cloneDeep } from 'lodash-es';
import { DgControl } from '../../../../utils/dg-control';
import { HeaderDragDropManager } from '../../header/drag-drop/dragAndDrapManager';
import { DomService } from '@farris/designer-services';

export default class FdModalFooterComponent extends FarrisDesignBaseNestedComponent {

    /** 当前表单的展示模式，弹出类modal/独立页签类page/侧边滑出类slide 。
     * 优先取控件所属组件的展示类型，若没有配置，则取当前表单的展示类型
     */
    currentFormMode;

    // toolbar数据
    toolbarDatas;

    component;
    footerToolBar: FdHeaderToolBarComponent;


    /** 判断当前容器是否是固定的上下文的中间层级，这种容器不支持移动、不支持删除、并且隐藏间距 */
    private isInFixedContextRules = false;

    private dragManager: HeaderDragDropManager;

    constructor(component: any, options: any) {
        super(component, options);

        // 虽然类别为“容器”，但是实际没有子级节点
        this.category = 'container';

        this.dragManager = new HeaderDragDropManager(this);
        this.isInFixedContextRules = this.dragManager.checkIsInFixedContextRules();
    }

    /**
     * 为了适配按钮大小，增加ide-header-toolbar-XX 样式
     */
    getClassName(): string {
        let clsName = super.getClassName();
        if (this.component.toolbarBtnSize && this.component.toolbarBtnSize !== 'default') {
            clsName += ' ide-header-toolbar-' + this.component.toolbarBtnSize;
        }
        return clsName;
    }

    getDefaultSchema(): any {
        return ModalFooterSchema;
    }

    getTemplateName(): string {
        return 'ModalFooter';
    }
    hideNestedPaddingInDesginerView(): boolean {
        return true;
    }
    // 初始化
    init(): void {
        this.components = [];

        this.initToolbar();
        super.init();
    }
    private initToolbar() {
        // 当前showType
        const domService = this.options.designerHost.getService('DomService');
        this.currentFormMode = domService.module.showType || 'page';
        const comp = domService.getComponentByVMId(this.viewModelId);
        if (comp && comp.showType) {
            this.currentFormMode = comp.showType;
        }

        this.toolbarDatas = this.assembleHeaderToolbar();
        // 创建工具栏组件
        const toolBarComponent = this.getResponseToolbarStr();
        const options = Object.assign({}, this.options, { childComponents: [], parent: this, showType: this.currentFormMode, popDirection: 'top' });
        if (!this.footerToolBar) {
            this.footerToolBar = new FdHeaderToolBarComponent(toolBarComponent, options);
        } else {
            this.footerToolBar.reInit(toolBarComponent, this.currentFormMode);
        }
        this.footerToolBar.init();
    }
    // 渲染模板
    render(children): any {
        this.initToolbar();
        return super.render(children || this.renderTemplate('ModalFooter', {
            toolbarDatas: this.toolbarDatas,
            currentFormMode: this.currentFormMode,
            footerToolBar: this.footerToolBar,
            getResponseToolbarStr: () => this.getResponseToolbarStr()
        }));
    }
    // 绑定事件
    attach(element: any): any {
        // 必写
        const superAttach: any = super.attach(element);

        // 工具栏绑定事件
        const footerToolBarEle = element.querySelector('.farris-component-ModalFooterToolBar');
        if (footerToolBarEle) {
            this.footerToolBar.attach(footerToolBarEle);
        }

        // 将按钮的实例追加到header中，是为了从代码编辑器切换到可视化设计器时重新选中按钮
        if (this.footerToolBar) {
            const toolbarItemCmps = this.footerToolBar.components || [];
            this.components = this.components.concat(toolbarItemCmps);
        }

        this.setUnusedButtonsBasicInfoMap();

        // 必写
        return superAttach;
    }
    /**
     * 组装属性面板配置数据
     */
    getPropertyConfig(): ElementPropertyConfig[] {
        const serviceHost = this.options.designerHost;
        const prop: ModalFooterProp = new ModalFooterProp(serviceHost, this.viewModelId, this.componentId);
        const propertyConfig: ElementPropertyConfig[] = prop.getPropConfig(this.component);
        return propertyConfig;
    }
    // 构造Toolbar
    private assembleHeaderToolbar() {
        const toolbar = this.options.designerHost.getService('DomService').module.toolbar;
        if (!toolbar || !toolbar.items || !toolbar.items[this.viewModelId] ||
            !toolbar.configs || !toolbar.configs[this.currentFormMode] ||
            !toolbar.configs[this.currentFormMode][this.id]) {
            return [];
        }
        const buttonConfig = toolbar.configs[this.currentFormMode][this.id] as string[];
        if (!buttonConfig) {
            return [];
        }
        const toolbarItems = [];
        buttonConfig.forEach(buttonId => {
            const buttonInfo = toolbar.items[this.viewModelId].find(item => buttonId === item.id);
            if (buttonInfo) {
                toolbarItems.push(buttonInfo);
            }
        });
        return this.assembleToolBarItem(toolbarItems);
    }
    // 构造ToolbarItem
    private assembleToolBarItem(items): any[] {
        if (!items || items.length === 0) {
            return [];
        }
        const data = [];
        items.forEach(item => {
            const dataItem = cloneDeep(item);

            if (item.items && item.items.length > 0) {
                dataItem.isDP = true;
                dataItem.children = this.assembleToolBarItem(item.items);
            }

            data.push(dataItem);
        });
        return data;
    }
    /**
     * 获取工具栏数据
     */
    getResponseToolbarStr() {
        const toolBar = {
            id: 'footer-toolbar' + Math.random().toString(36).slice(2, 6),
            type: 'ModalFooterToolBar',
            appearance: {
                class: `f-toolbar ml-auto ${this.component.toolbarCls}`
            },
            title: '底部工具栏',
            items: this.toolbarDatas,
            toolbarCls: this.component.toolbarCls,
            toolbarBtnSize: this.component.toolbarBtnSize,
            toolbarPopDirection: this.component.toolbarPopDirection
        };
        return toolBar;
    }


    /**
     * 属性变更后
     * @param changeObject 变更集
     */
    onPropertyChanged(changeObject: FormPropertyChangeObject): void {
        if (['custom', 'appearance', 'toolbarPropsOnHeader'].includes(changeObject.categoryId)) {

            // 变更按钮个数，需要重新组装toolbarDatas数据
            if (changeObject.propertyID === 'toolbarDatas') {
                this.toolbarDatas = this.assembleHeaderToolbar();
            }
            this.redraw();
        }
    }
    checkCanDeleteComponent(): boolean {
        if (this.isInFixedContextRules) {
            return false;
        }
        return true;
    }
    checkCanMoveComponent(): boolean {
        if (this.isInFixedContextRules) {
            return false;
        }
        return true;
    }
    canAccepts(sourceElement: BuilderHTMLElement, targetElement?: BuilderHTMLElement): boolean {
        return false;
    }
    /**
     * 点击控件时计算控件工具栏位置
     */
    setPositionOfBtnGroup() {
        super.setPositionOfBtnGroup();

        //  footer重绘后要重新计算内部工具栏的操作图标位置
        if (this.footerToolBar) {
            const toolbarEle = this.element.querySelector(`.dgComponentSelected[controltype='${DgControl.ModalFooterToolBar.type}']`);
            if (toolbarEle) {
                const toolbar = toolbarEle.querySelector('.component-btn-group') as HTMLElement;
                if (toolbar) {
                    toolbar.style.display = '';
                    const toolbarRect = toolbar.getBoundingClientRect();

                    const divPanel = toolbar.querySelector('div');
                    const divPanelRect = divPanel.getBoundingClientRect();

                    divPanel.style.top = toolbarRect.top + 'px';
                    divPanel.style.left = (toolbarRect.left - divPanelRect.width) + 'px';
                }
            }

        }
    }
    private setUnusedButtonsBasicInfoMap() {
        const toolbar = this.options.designerHost.getService('DomService').module.toolbar;

        if (!toolbar || !toolbar.items || !toolbar.items[this.viewModelId] ||
            !toolbar.configs || !toolbar.configs[this.currentFormMode] ||
            !toolbar.configs[this.currentFormMode][this.id]) {
            return [];
        }
        const buttonConfig = toolbar.configs[this.currentFormMode][this.id] as string[];
        if (!buttonConfig) {
            return [];
        }

        const domService = this.options.designerHost.getService('DomService') as DomService;

        // 全局按钮若未被使用，仍需要设置路径信息，目的是为了方便交互面板显示
        let allUsedButtons = [];
        Object.keys(toolbar.configs[this.currentFormMode]).map(controlId => {
            allUsedButtons = allUsedButtons.concat(toolbar.configs[this.currentFormMode][controlId]);
        });


        toolbar.items[this.viewModelId].map(button => {
            if (!allUsedButtons.includes(button.id)) {
                domService.controlBasicInfoMap.set(button.id, {
                    showName: button.text,
                    parentPathName: button.text
                });
            }
        });
    }
}
